"use client"

import { useEffect, useState } from "react"
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts"
import { Activity, BookOpen, Clock, Users, AlertTriangle, CheckCircle2, XCircle } from "lucide-react"

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { AttentionAlert } from "@/components/attention-alert"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { DashboardCharts } from "@/components/dashboard-charts"
// 修改课程章节数据
const courseChapters = [
  { id: 1, title: "第一章：微积分基础", completed: true, current: false },
  { id: 2, title: "第二章：导数与微分", completed: true, current: false },
  { id: 3, title: "第三章：多元函数微分学", completed: false, current: true },
  { id: 4, title: "第四章：不定积分", completed: false, current: false },
  { id: 5, title: "第五章：定积分及其应用", completed: false, current: false },
]

// 修改当前课程小节
const currentLessons = [
  { id: 1, title: "3.1 多元函数的概念", completed: true },
  { id: 2, title: "3.2 偏导数", completed: false, current: true },
  { id: 3, title: "3.3 全微分", completed: false },
  { id: 4, title: "3.4 多元函数的极值", completed: false },
]

// 注意力详细数据
const attentionDetailData = [
  { name: "专注", value: 65, color: "#4ade80" },
  { name: "分心", value: 25, color: "#fb923c" },
  { name: "离开", value: 10, color: "#f87171" },
]

// Simulated data for the dashboard
const generateRandomData = () => {
  return {
    attendanceCount: Math.floor(Math.random() * 5) + 25,
    totalStudents: 30,
    attentionScore: Math.floor(Math.random() * 30) + 70,
    participationRate: Math.floor(Math.random() * 20) + 60,
    progressPercentage: Math.floor(Math.random() * 15) + 40,
    timeRemaining: 25 - Math.floor(Math.random() * 5),
    attentionDetails: [
      { name: "专注", value: Math.floor(Math.random() * 20) + 55, color: "#4ade80" },
      { name: "分心", value: Math.floor(Math.random() * 15) + 15, color: "#fb923c" },
      { name: "离开", value: Math.floor(Math.random() * 10) + 5, color: "#f87171" },
    ],
    behaviorCounts: {
      questions: Math.floor(Math.random() * 5) + 3,
      answers: Math.floor(Math.random() * 10) + 5,
      distractions: Math.floor(Math.random() * 8) + 2,
    },
  }
}

// Simulated engagement data over time
const engagementData = Array.from({ length: 10 }, (_, i) => ({
  time: `${i * 5}分钟`,
  注意力: Math.floor(Math.random() * 30) + 70,
  参与度: Math.floor(Math.random() * 20) + 60,
}))

// 修改学科表现数据
const subjectData = [
  { name: "高等数学", 平均分: 85, 最高分: 98 },
  { name: "大学英语", 平均分: 78, 最高分: 95 },
  { name: "程序设计", 平均分: 82, 最高分: 97 },
  { name: "数据结构", 平均分: 88, 最高分: 99 },
  { name: "计算机网络", 平均分: 76, 最高分: 92 },
]

export default function ClassroomDashboard() {
  const [data, setData] = useState(generateRandomData())
  const [showAlert, setShowAlert] = useState(false)

  // Simulate real-time data updates
  useEffect(() => {
    const interval = setInterval(() => {
      const newData = generateRandomData()
      setData(newData)

      // Show attention alert if attention score drops below threshold
      if (newData.attentionScore < 75 && Math.random() > 0.7) {
        setShowAlert(true)
        setTimeout(() => setShowAlert(false), 5000)
      }
    }, 5000)

    return () => clearInterval(interval)
  }, [])

  return (
    <div className="space-y-6">
      {showAlert && <AttentionAlert />}

      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">出勤率</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {data.attendanceCount}/{data.totalStudents}
            </div>
            <p className="text-xs text-muted-foreground">
              出勤率 {Math.round((data.attendanceCount / data.totalStudents) * 100)}%
            </p>
            <Progress className="mt-3" value={(data.attendanceCount / data.totalStudents) * 100} />
            <div className="mt-3 flex justify-between text-xs text-muted-foreground">
              <span>缺勤: {data.totalStudents - data.attendanceCount}人</span>
              <span>迟到: 2人</span>
              <span>请假: 1人</span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">注意力指数</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{data.attentionScore}%</div>
            <p className="text-xs text-muted-foreground">
              {data.attentionScore > 80 ? "良好" : data.attentionScore > 70 ? "一般" : "需要提升"}
            </p>
            <Progress
              className="mt-3"
              value={data.attentionScore}
              color={
                data.attentionScore > 80 ? "bg-green-500" : data.attentionScore > 70 ? "bg-yellow-500" : "bg-red-500"
              }
            />
            <div className="mt-3 flex justify-between text-xs">
              <span className="flex items-center gap-1 text-green-600">
                <CheckCircle2 className="h-3 w-3" /> 专注: {data.attentionDetails[0].value}%
              </span>
              <span className="flex items-center gap-1 text-orange-500">
                <AlertTriangle className="h-3 w-3" /> 分心: {data.attentionDetails[1].value}%
              </span>
              <span className="flex items-center gap-1 text-red-500">
                <XCircle className="h-3 w-3" /> 离开: {data.attentionDetails[2].value}%
              </span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">课程进度</CardTitle>
            <BookOpen className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{data.progressPercentage}%</div>
            <div className="flex items-center justify-between">
              <p className="text-xs text-muted-foreground">当前章节：第三章 第二节</p>
              <Badge variant="outline" className="text-xs">
                进行中
              </Badge>
            </div>
            <Progress className="mt-3" value={data.progressPercentage} />
            <div className="mt-3 text-xs text-muted-foreground">
              <div className="flex justify-between">
                <span>已完成知识点: 12/25</span>
                <span>剩余: 13</span>
              </div>
              <Button variant="link" size="sm" className="h-auto p-0 text-xs">
                查看详细进度
              </Button>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">剩余时间</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{data.timeRemaining} 分钟</div>
            <div className="flex items-center justify-between">
              <p className="text-xs text-muted-foreground">总课时：45分钟</p>
              <Badge variant="outline" className="text-xs">
                {data.timeRemaining < 10 ? "即将结束" : "进行中"}
              </Badge>
            </div>
            <Progress className="mt-3" value={(data.timeRemaining / 45) * 100} />
            <div className="mt-3 flex justify-between text-xs text-muted-foreground">
              <span>开始时间: 10:00</span>
              <span>结束时间: 10:45</span>
            </div>
          </CardContent>
        </Card>
      </div>
      <div className="mt-6 grid gap-6 grid-cols-1">
          <DashboardCharts />
      </div>
      <div className="grid gap-6 md:grid-cols-3">
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>学生参与度趋势</CardTitle>
            <CardDescription>课堂期间的注意力和参与度变化</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={engagementData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="注意力" stroke="#8884d8" activeDot={{ r: 8 }} />
                <Line type="monotone" dataKey="参与度" stroke="#82ca9d" />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>注意力分布</CardTitle>
            <CardDescription>学生当前注意力状态分布</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={data.attentionDetails}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                >
                  {data.attentionDetails.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>课程进度详情</CardTitle>
            <CardDescription>当前课程章节完成情况</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div>
                <h4 className="mb-2 text-sm font-medium">章节进度</h4>
                <div className="space-y-2">
                  {courseChapters.map((chapter) => (
                    <div key={chapter.id} className="flex items-center gap-2">
                      {chapter.completed ? (
                        <CheckCircle2 className="h-4 w-4 text-green-500" />
                      ) : chapter.current ? (
                        <Activity className="h-4 w-4 text-blue-500" />
                      ) : (
                        <Clock className="h-4 w-4 text-gray-400" />
                      )}
                      <span className={`text-sm ${chapter.current ? "font-medium" : ""}`}>{chapter.title}</span>
                      {chapter.current && (
                        <Badge variant="secondary" className="ml-auto">
                          进行中
                        </Badge>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              <Separator />

              <div>
                <h4 className="mb-2 text-sm font-medium">当前小节：第三章 乘法</h4>
                <div className="space-y-2">
                  {currentLessons.map((lesson) => (
                    <div key={lesson.id} className="flex items-center gap-2">
                      {lesson.completed ? (
                        <CheckCircle2 className="h-4 w-4 text-green-500" />
                      ) : lesson.current ? (
                        <Activity className="h-4 w-4 text-blue-500" />
                      ) : (
                        <Clock className="h-4 w-4 text-gray-400" />
                      )}
                      <span className={`text-sm ${lesson.current ? "font-medium" : ""}`}>{lesson.title}</span>
                      {lesson.current && (
                        <Badge variant="secondary" className="ml-auto">
                          当前
                        </Badge>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              <div className="pt-2">
                <Button variant="outline" size="sm" className="w-full">
                  查看完整课程大纲
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>课堂行为统计</CardTitle>
            <CardDescription>学生互动和行为分析</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="grid grid-cols-3 gap-4">
                <div className="rounded-lg border p-3 text-center">
                  <div className="text-2xl font-bold">{data.behaviorCounts.questions}</div>
                  <div className="text-xs text-muted-foreground">提问次数</div>
                </div>
                <div className="rounded-lg border p-3 text-center">
                  <div className="text-2xl font-bold">{data.behaviorCounts.answers}</div>
                  <div className="text-xs text-muted-foreground">回答次数</div>
                </div>
                <div className="rounded-lg border p-3 text-center">
                  <div className="text-2xl font-bold">{data.behaviorCounts.distractions}</div>
                  <div className="text-xs text-muted-foreground">分心次数</div>
                </div>
              </div>

              <div>
                <h4 className="mb-2 text-sm font-medium">学科表现</h4>
                <ResponsiveContainer width="100%" height={200}>
                  <BarChart data={subjectData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="平均分" fill="#8884d8" />
                    <Bar dataKey="最高分" fill="#82ca9d" />
                  </BarChart>
                </ResponsiveContainer>
              </div>

              <div className="pt-2">
                <Button variant="outline" size="sm" className="w-full">
                  查看详细行为分析
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div> */}


    </div>
  )
}
